package com.surveillance.controllers;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.surveillance.BO.EtudiantBO;
import com.surveillance.BO.SalleBO;
import com.surveillance.entities.Etudiant;
import com.surveillance.entities.Salle;
import com.surveillance.util.ArrayShuffling;
import com.surveillance.util.LoadBeans;
import com.surveillance.util.SalleBundle;
import com.surveillance.util.SalleEtudiantTuple;
import com.surveillance.util.NiveauSpecialiteBundle;
import com.surveillance.util.SetOvSalles;

@Controller
public class AffectationEtudiantsController {
	EtudiantBO etudiantBO = (EtudiantBO) LoadBeans.getEtudiantBO();
	SalleBO salleBO = (SalleBO) LoadBeans.getSalleBO();

	@RequestMapping(value = "/affectationEtudiants-salle", method = RequestMethod.GET)
	String renderStudentsAffectationSalle(ModelMap model, HttpSession session) {
		model.addAttribute("availableSalles",
				session.getAttribute("availableSalles"));
		model.addAttribute("studentNumber",
				session.getAttribute("studentNumber"));
		model.addAttribute("salleBundle", session.getAttribute("salleBundle"));
		return "affectationEtudiants-salle";
	}

	@RequestMapping(value = "/affectationEtudiants-salle", method = RequestMethod.POST)
	public String triggerAffectation(
			@ModelAttribute("availableSalles") SetOvSalles setOvSalles,
			ModelMap model, HttpSession session) {//
		// fetching students
		int niveau = (Integer) session.getAttribute("niveau");
		System.out.println("printing niveau" + niveau);
		Boolean isMedcine = (Boolean) session.getAttribute("isMedcine");
		System.out.println("printing isMedcine" + isMedcine);
		Salle tempSalle = new Salle();
		ArrayList<Salle> fetchedSalles = new ArrayList<Salle>();
		for (int i = 0; i < setOvSalles.getSalles().size(); i++) {
			if(setOvSalles.getSalles().get(i).getId()!=null){
				tempSalle = salleBO.findByID(setOvSalles.getSalles().get(i).getId());
				tempSalle.setCapaciteE(setOvSalles.getSalles().get(i).getCapaciteE());
				salleBO.update(tempSalle);
				fetchedSalles.add(tempSalle);
			}
		}

		ArrayList<SalleEtudiantTuple> salleEtudiantsTuples = salleBO
				.affectationEtudiant(niveau, isMedcine, fetchedSalles);
		model.addAttribute("salleEtudiantsTuples", salleEtudiantsTuples);
		return "affectationEtudiants-table";
	}

}
